package com.missmess.opengldemo;

import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends ListActivity {

    private List<Map<String, String>> mActs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        init();
    }

    private void init() {
        mActs = getActs();
        SimpleAdapter adapter = new SimpleAdapter(this, mActs, android.R.layout.simple_selectable_list_item, new String[]{"name"}, new int[]{android.R.id.text1});
        setListAdapter(adapter);
        getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String act = mActs.get(position).get("act");
                try {
                    startActivity(new Intent(MainActivity.this, Class.forName(act)));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private List<Map<String, String>> getActs() {
        ArrayList<Map<String, String>> acts = new ArrayList<>();
        Intent filterIntent = new Intent("demo_action", null);
        filterIntent.addCategory("opengl_demo");

        PackageManager pm = getPackageManager();
        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(filterIntent, 0);
        for(ResolveInfo info : resolveInfos) {
            HashMap<String, String> map = new HashMap<>();
            String name = info.activityInfo.name;
            String[] mi = name.split("\\.");
            map.put("name", mi[mi.length - 1]);
            map.put("act", name);
            acts.add(map);
        }

        return acts;
    }
}
